﻿using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;

using NJ.Common.Log;
using NJ.Common.Network;
using NJ.Dto.Log;
using NJ.Service.Log;

namespace NJ.Web.Filter
{
    /// <summary>
    /// 操作监控
    /// </summary>
    public class ActionMonitoringAttribute : ActionFilterAttribute
    {
        public ILogger logger { get; set; }

        public ILogService logService { get; set; }

        Stopwatch stopWatch = new Stopwatch();

        /// <summary>
        /// 操作描述（增加 删除 修改）
        /// </summary>
        public string ActionDesc { get; set; }

        public ActionMonitoringAttribute()
        {
            stopWatch = new Stopwatch();
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopWatch.Start();
            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopWatch.Stop();
            var method = filterContext.HttpContext.Request.HttpMethod;
            var requestUrl = filterContext.HttpContext.Request.Url.AbsoluteUri;
            var query = filterContext.HttpContext.Request.Url.Query;
            var form = string.Join("&", filterContext.HttpContext.Request.Form.AllKeys.Select(t => $"{t}={filterContext.HttpContext.Request.Form[t]}"));
            var client = filterContext.HttpContext.Request.UserAgent;
            var userName = filterContext.Controller.ViewData["UserName"];
            logService.AddActionLogAsync(new ActionLogDto
            {
                ClientIP = Net.Ip,
                ClientName = client,
                ActionDesc = ActionDesc,
                Form = form,
                Method = method,
                Query = query,
                RequestUrl = requestUrl,
                UserName = userName.ToString(),
                ElapsedTime = stopWatch.ElapsedMilliseconds
            });
            logger.Warn($"用户名：{userName}；操作描述：{ActionDesc}；操作耗时：{stopWatch.ElapsedMilliseconds}ms");
            base.OnActionExecuted(filterContext);
        }
    }
}